<template>
	<!-- 投放系统-推广列表 -->
	<d2-container class="d-flex flex-column mod-sys__user">
		<template v-if="$hasPermission('delivery:dataSpread:index')">
			<div class="d-flex b-s mt-2 mb-10 j-sb" slot="header">
				<el-form class="d-flex b-s" :inline="true" size="small" :model="dataForm"
					@keyup.enter.native="searchTableList()" @submit.native.prevent>
					<el-form-item label="推广链接ID">
						<el-input v-model="dataForm.id" placeholder="推广链接ID" clearable />
					</el-form-item>
					<el-form-item label="推广链接名称">
						<el-input v-model="dataForm.keyword" placeholder="推广链接名称" clearable />
					</el-form-item>
					<el-form-item  label="短剧名称">
						<el-select clearable v-model="dataForm.playlet_id" placeholder="请选择短剧" >
							<el-option v-for="(item,index) in playletList" :key="index" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button icon="el-icon-search" type="primary"
							@click="searchTableList()">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="success" icon="el-icon-circle-plus-outline" v-show="$hasPermission('delivery:dataSpread:create')"
							@click="addOrUpdateData()">新增推广</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="success" icon="el-icon-finished" v-show="$hasPermission('delivery:dataSpread:batchSettings')"
							@click="batchSetting()">批量配置</el-button>
					</el-form-item>
				</el-form>
				<div class="d-flex">
					<vxe-toolbar ref="toolbarRef" custom :refresh="{ queryMethod: getTableList,code:'query' }"></vxe-toolbar>
				</div>
			</div>
			<vxe-table ref="xTable" key="delivery_dataSpread" border height="100%" resizable size="medium"
				@checkbox-all="selectAllEvent"
				@checkbox-change="selectChangeEvent"
				:loading="tableLoading" :loading-config="{icon: 'vxe-icon-indicator roll', text: '正在拼命加载中...'}"
				:data="dataList" cell-class-name="py-10">
				<vxe-column type="checkbox" field="checkbox" width="60" align="center"></vxe-column>
				<vxe-column width="150" field="id" title="推广链接ID" sortable align="center"></vxe-column>
				<vxe-column width="260" field="name" title="推广链接名称" align="center"></vxe-column>
				<vxe-column header-class-name="delivery_dataSpread_aname" width="150" field="applet_name" title="小程序名称" align="center"
				:filters="appletFilters" :filter-method="filterApplet"></vxe-column>
				<vxe-column header-class-name="playlet_name" width="260" field="playlet_name" title="短剧名称" align="center"
				:filters="playlet_name_filters" :filter-method="filterPlayletName"></vxe-column>
				<vxe-column header-class-name="recharge_template_name" width="180" field="recharge_template_name" title="首充模板名称" align="center"
				:filters="recharge_template_name_filters" :filter-method="rtnFiltersFn"
				></vxe-column>
				<vxe-column header-class-name="recharge_assistant_template_name" width="180" field="recharge_assistant_template_name" title="复充模板名称" align="center"
				:filters="recharge_assistant_template_name_filters" :filter-method="ratnFiltersFn"
				></vxe-column>
				<vxe-column header-class-name="retention_template_name" width="180" field="retention_template_name" title="挽留模板名称" align="center"
				:filters="retention_template_name_filters" :filter-method="retnFiltersFn"></vxe-column>
				<vxe-column width="140" field="ad_account" title="广告账户ID" sortable align="center"></vxe-column>
				<vxe-column width="120" field="backhaul_setting_name" title="回传配置模板" sortable align="center"></vxe-column>
				<vxe-column width="120" field="playlet_number_num" title="收费集数" sortable align="center"></vxe-column>
				<vxe-column width="120" field="playlet_number_num_pay" title="单集收费" sortable align="center"></vxe-column>
				<vxe-column width="150" field="company_name" title="公司名称" align="center"></vxe-column>
				<vxe-column width="150" field="playlet_number_name" title="剧集名称" align="center"></vxe-column>
				<vxe-column width="120" field="playlet_number" title="剧集集数" sortable align="center"></vxe-column>
				<vxe-column width="160" field="created_at" title="创建时间" sortable cell-type="string" align="center"></vxe-column>
				<vxe-column width="160" field="updated_at" title="修改时间" sortable cell-type="string" align="center"></vxe-column>
				<vxe-column v-if="!tableLoading||(dataList.length&&$hasPermissionNum(['delivery:dataSpread:copy','delivery:dataSpread:update','delivery:payment:index','delivery:dataSpread:monitoringLink','delivery:dataSpread:promotionLink','delivery:dataSpread:delete']))" 
				title="操作" fixed="right" :width="$hasPermissionNum(['delivery:dataSpread:copy','delivery:dataSpread:update','delivery:payment:index','delivery:dataSpread:monitoringLink','delivery:dataSpread:promotionLink','delivery:dataSpread:delete'])*90" align="center" cell-class-name="py-10">
					<template v-slot="{ row }">
						<el-button-group>
							<el-button size = "small" round icon="el-icon-copy-document"
							v-if="$hasPermission('delivery:dataSpread:copy')"
							@click="copyTableData(row)" type="primary">复制</el-button>
							<el-button size = "small" round icon = "el-icon-edit"
							v-if="$hasPermission('delivery:dataSpread:update')"
							@click="addOrUpdateData(row)" type="primary">编辑</el-button>
							<el-button size = "small" round icon = "el-icon-s-order"
							v-if="$hasPermission('delivery:payment:index')"
							@click="showOrderData(row)" type="primary">订单数据</el-button>
							<el-button size = "small" round icon = "el-icon-view" 
							v-if="$hasPermission('delivery:dataSpread:monitoringLink')"
							@click="monitorUpdateData(row)" type="primary">监测链接</el-button>
							<el-button size = "small" round icon = "el-icon-view"
							v-if="$hasPermission('delivery:dataSpread:promotionLink')"
							@click="putUpdateData(row)" type="primary">投放链接</el-button>
							<!-- <el-button size = "small" round icon = "el-icon-delete"
							v-if="$hasPermission('delivery:dataSpread:delete')"
							@click = "deleteHandleSetter(row)" type="danger">删除</el-button> -->
							<el-button v-if="$hasPermission('delivery:dataSpread:delete') || $hasPermission('delivery:dataSpread:accountBind')" size="small" round type="info" plain style="padding:0;height: 32px;width: 60px;">
								<el-dropdown style="font-size: 12px;color:#000;width: 100%;height: 100%;">
									<span class="el-dropdown-link" style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;">
										更多<i class="el-icon-arrow-down el-icon--right"></i>
									</span>
									<el-dropdown-menu slot="dropdown">
										<el-dropdown-item>
											<el-button size="small"  icon="el-icon-link"
												v-if="$hasPermission('delivery:dataSpread:accountBind') && row.ad_account"
												@click = "accountBindHandleSetter(row)" type="primary">解绑</el-button>
										</el-dropdown-item>
										<el-dropdown-item>
											<el-button size="small"  icon="el-icon-delete"
												v-if="$hasPermission('delivery:dataSpread:delete')"
												@click = "deleteHandleSetter(row)" type="danger">删除</el-button>
										</el-dropdown-item>
									</el-dropdown-menu>
								</el-dropdown>
							</el-button>
						</el-button-group>
					</template>
				</vxe-column>
				<template #empty>
					<div class="d-flex flex-row a-center j-center font-md">
						<div class="d-flex">
							暂时没有数据~
						</div>
					</div>
				</template>
			</vxe-table>
			<!-- 分页 -->
			<div class="d-flex" slot="footer">
				<vxe-pager background size="medium" align="right" :border="false" :current-page="dataForm.page"
					:page-size="dataForm.pageSize" :total="total" :pageSizes="[20,50,100,150,200]"
					:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
					@page-change="handlePageChange">
				</vxe-pager>
			</div>
			<!-- 新增/修改弹窗 -->
			<dataSpread-add-or-update v-if="addOrUpdateVisible" ref="addOrUpdateDialog" @refreshDataList="getTableList($event)"></dataSpread-add-or-update>
			<!-- 订单数据弹窗 -->
			<order-data v-if="orderDataVisible" ref="orderDataDialog" @refreshDataList="getTableList()"></order-data>
			<!-- 批量配置弹窗 -->
			<dataSpread-batch-setting v-if="batchSettingVisible" ref="batchSettingDialog" @refreshDataList="getTableList()"></dataSpread-batch-setting>
			<!-- 监测链接弹窗 -->
			<monitor-update v-if="monitorVisible" ref="monitorDialog" @refreshDataList="getTableList()"></monitor-update>
			<!-- 投放链接弹窗 -->
			<put-update v-if="putVisible" ref="putDialog"></put-update>
		</template>
		<template v-else>
			<div class="d-flex a-center j-center h-100 b-s flex-column">
				<img class="d-flex b-s mt-2 mb-10" src="../../../public/image/download.png" alt="没有访问权限" style="width: 300px;">
				<div class="d-flex">抱歉，您没有访问权限</div>
			</div>
		</template>
	</d2-container>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import mixinViewModule from '@/mixins/view-module'
	import DataSpreadAddOrUpdate from './dataSpread-add-or-update'
	import OrderData from './orderData'
	import DataSpreadBatchSetting from './dataSpread-batchSetting'
	import MonitorUpdate from './monitor-update'
	import PutUpdate from './put-update'
	export default {
		mixins: [mixinViewModule],
		components: {
			DataSpreadAddOrUpdate,
			OrderData,
			DataSpreadBatchSetting,
			MonitorUpdate,
			PutUpdate
		},
		data() {
			return {
				playletList:[],
				
				tableLoading:false,
				orderDataVisible:false,
				addOrUpdateVisible:false,
				batchSettingVisible:false,
				monitorVisible:false,
				putVisible:false,
				templateId:'',
				records: [],
				checkIDArray: [],
				curent: 0,
				total: 0,
				firstConvention:{},
				playlet_name_filters:[],//短剧名称筛选下拉框
				appletFilters:[],//小程序名称筛选数组
				recharge_template_name_filters:[],
				recharge_assistant_template_name_filters:[],
				retention_template_name_filters:[],//挽留筛选下拉框
				dataForm: {
					page: 1,
					pageSize: 20,
					keyword:'',
					playlet_id:''
				},
				templateForm: {},
				// 增改
				dataList: [],
			}
		},
		created() {
			this.dataForm['applet_ids'] = this.info.applet_id;
			this.dataForm['delivery_user_id'] = this.info.delivery_user_id;
		},
		mounted(){
		},
		watch: {
			dataList:{
				handler(newValue) {
					setTimeout(()=>{
						this.getfilterData('playlet_name');
						this.getfilterData('recharge_template_name');
						this.getfilterData('recharge_assistant_template_name');
						this.getfilterData('retention_template_name');
						this.getAppletFilters(this.dataForm.applet_id,newValue);
					},300)
				},
				deep: true
			},
			'info.applet_id': {
				handler(newVal,oldVal) {
					if(newVal!=oldVal){
						if (typeof newVal == 'number') {
							console.warn('========监听小程序ID发生变化=======');
							console.log(newVal);
							this.records = [];
							this.checkIDArray = [];
							this.dataForm['applet_ids'] = newVal;
							this.$forceUpdate();
							if(this.$hasPermission('delivery:dataSpread:index')){
								if(this.$hasPermission('delivery:delivery:teamList')){
									if(Array.isArray(this.dataForm['delivery_user_id'])){
										this.getTableList(true);
										this.playletListFn();
									}
									return;
								}
								this.getTableList(true);
								this.playletListFn();
							}
						}
					}
				},
				deep: true,
				immediate: true
			},
			'info.delivery_user_id': {
				handler(newVal,oldVal) {
					if(newVal!=oldVal){
						if (Array.isArray(newVal)) {
							console.warn('========投放组员ID发生变化=======');
							console.log(newVal);
							this.records = [];
							this.checkIDArray = [];
							this.dataForm['delivery_user_id'] = newVal;
							this.$forceUpdate();
							if(this.$hasPermission('delivery:dataSpread:index')){
								this.getTableList(true);
								this.playletListFn();
							}
						}
					}
				},
				deep: true,
				immediate: true
			},
			templateForm: {
				handler(newValue) {
					console.warn('监听到了');
					this.dataForm = [];
					if(Array.isArray(newValue.convention)){
						if(newValue.convention.length){
							this.dataForm.push(...newValue.convention);
						}
					}
					//超级
					if(Array.isArray(newValue.member)){
						let memberLen = newValue.member.length;
						if(memberLen){
							for (let i = 0; i < memberLen; i++) {
								if(newValue.member[i].status){
									this.dataForm.push(newValue.member[i]);
								}
							}
						}
					}
					//整剧购买
					if(Array.isArray(newValue.promotion)){
						let promotionLen = newValue.promotion.length;
						if(promotionLen){
							for (let i = 0; i < promotionLen; i++) {
								if(newValue.promotion[i].status){
									this.dataForm.unshift(newValue.promotion[i]);
								}
							}
						}
					}
					console.log(this.dataForm);
				},
				deep: true
			}
		},
		computed: {
			...mapState('d2admin/user', [
				'info'
			])
		},
		methods: {
			...mapMutations({
				pageInit: 'd2admin/page/init',
				headerSet: 'd2admin/menu/headerSet'
			}),
			searchTableList(){
				this.$refs.xTable.clearFilter();
				this.getTableList(true);
			},
			getAppletFilters(applet_id,datalist){
				setTimeout(()=>{
					let anameDom = document.querySelector('.delivery_dataSpread_aname span.vxe-cell--filter');
					if(applet_id==1||!applet_id){
						if(Array.isArray(this.info.applet)&&this.info.applet.length){
							this.appletFilters = this.info.applet.filter((item)=>{
								return item.value&&item.value!=1
							})
							console.log(this.appletFilters);
							if(anameDom&&datalist.length){
								anameDom.style.display = 'inline-block';
							}else{
								anameDom.style.display = 'none';
							}
							return;
						}
					}
					this.appletFilters = [];
					if(anameDom){
						anameDom.style.display = 'none';
					}
				},300)
			},
			//短剧名称筛选
			filterPlayletName({ option, row }) {
				return row.playlet_name == option.label
			},
			//小程序名称筛选
			filterApplet ({ option, row }) {
				return row.applet_name == option.label
			},
			//获取短剧列表
			async playletListFn() {
				const pRes = await this.$axios.get(`/api/delivery/getplayletInfo?applet_ids=${this.info.applet_id}`);
				console.log(pRes);
				if(Array.isArray(pRes)) {
					if (pRes.length) {
						this.playletList = pRes;
						return;
					}
				}
				this.playletList = [];
			},
		
			async copyTableData(row){
				console.log(250,row)
				this.addOrUpdateVisible = true;
				const id = row.id;
				const userRes = await this.$axios.get(`/api/delivery/dataSpread/update/${id}`,{});
				this.$nextTick(() => {
					this.$refs.addOrUpdateDialog.dataId = null;
					this.$refs.addOrUpdateDialog.diyname = row.name;
					// this.$refs.addOrUpdateDialog.dataForm = JSON.parse(JSON.stringify(userRes))
					this.$refs.addOrUpdateDialog.update(userRes);
				})
			},
			showOrderData(row){
				console.log(row);
				this.orderDataVisible = true;
				this.$nextTick(() => {
					this.$refs.orderDataDialog.orderDataForm.spread_id = row.id;
					this.$refs.orderDataDialog.init(row);
				})
			},
			selectAllEvent({
				checked
			}) {
				this.records = this.$refs.xTable.getCheckboxRecords();
				this.checkIDArray = this.records.map(element => element.id);
				console.log(this.checkIDArray);
			},
			selectChangeEvent({
				checked
			}) {
				this.records = this.$refs.xTable.getCheckboxRecords();
				this.checkIDArray = this.records.map(element => element.id);
				console.log(this.checkIDArray);
			},
			batchSetting(){
				if(!this.checkIDArray.length) {
					return this.$message({
						message: '请先勾选数据！',
						type: 'error',
						duration: 1000
					})
				}
				if(!this.dataForm.applet_ids||this.dataForm.applet_ids==1) {
					return this.$message({
						message: '请先选择小程序！',
						type: 'error',
						duration: 1000
					})
				}
				this.batchSettingVisible = true;
				this.$nextTick(() => {
					this.$refs.batchSettingDialog.appletId = this.dataForm.applet_ids;
					this.$refs.batchSettingDialog.dataForm.data_spread_ids = this.checkIDArray;
					this.$refs.batchSettingDialog.init();
					this.$refs.xTable.clearCheckboxRow();
					this.checkIDArray = [];
				})
			},
			clearCompanyFn(){
			},
			async getTableList(init=false) {
				if(init&&typeof init =='boolean'){
					this.dataForm.page = 1;
					if(this.$refs.xTable){
						this.$refs.xTable.clearFilter();
					}
				}
				console.log(359)
				this.tableLoading = true;
				const tableRes = await this.$axios.get('/api/delivery/dataSpread?'+this.$qs.stringify(this.dataForm));
				this.tableLoading = false;
				if(typeof tableRes == 'object' && tableRes!=null){
					this.total = tableRes.total;
					if(Array.isArray(tableRes.data)){
						let tdlen = tableRes.data.length;
						if(tdlen){
							this.dataList = tableRes.data;
							return
						}
					}
				}
				this.dataList = [];
			},
			//获取筛选下拉框数据
			getfilterData(field){
				this[field+'_filters'] = this.dataList.reduce((unique, current) => {
					const existing = unique.find(item => item.label === current[field]);
					if (!existing&&current[field]) {
						unique.push({
							value:current.id,
							label:current[field]
						});
					}
					return unique;
				}, []);
				let anameDom = document.querySelector('.'+field+' span.vxe-cell--filter');
				if(!this[field+'_filters'].length){
					if(anameDom) anameDom.style.display = 'none';
				}else{
					if(anameDom) anameDom.style.display = 'inline-block';
				}
			},
			//首充模板筛选
			rtnFiltersFn({ option, row }) {
				return row.recharge_template_name == option.label
			},
			//复充模板筛选
			ratnFiltersFn({ option, row }) {
				return row.recharge_assistant_template_name == option.label
			},
			//挽留模板筛选
			retnFiltersFn({ option, row }) {
				return row.retention_template_name == option.label
			},
			//新增/修改弹窗
			async addOrUpdateData(row) {
				this.$refs.xTable.clearFilter();
				console.log(row)
				this.addOrUpdateVisible = true;
				if (typeof row == 'object' && row!=null) {
					const id = row.id;
					const userRes = await this.$axios.get(`/api/delivery/dataSpread/update/${id}`);
					console.log(440,userRes)
					this.$nextTick(() => {
						this.$refs.addOrUpdateDialog.dataId = id;
						this.$refs.addOrUpdateDialog.diyname = null;
						this.$refs.addOrUpdateDialog.update(userRes);
					})
				} else {
					this.$nextTick(() => {
						this.$refs.addOrUpdateDialog.dataId = null;
						this.$refs.addOrUpdateDialog.diyname = null;
						this.$refs.addOrUpdateDialog.init()
					})
				}
			},
			//监测链接弹窗
			async monitorUpdateData(row) {
				console.log(row)
				this.monitorVisible = true;
				if (typeof row == 'object' && row!=null) {
					const id = row.id;
					const userRes = await this.$axios.get(`/api/delivery/dataSpread/monitoringLink/${id}`,{});
					this.$nextTick(() => {
						this.$refs.monitorDialog.name = row.name;
						this.$refs.monitorDialog.dataId = id;
						this.$refs.monitorDialog.update(userRes);
					})
				} else {
					this.$nextTick(() => {
						this.$refs.monitorDialog.dataId = null;
						this.$refs.monitorDialog.init()
					})
				}
			},
			//投放链接弹窗
			async putUpdateData(row) {
				console.log(row)
				this.putVisible = true;
				if (typeof row == 'object' && row!=null) {
					const id = row.id;
					const userRes = await this.$axios.get(`/api/delivery/dataSpread/promotionLink/${id}`,{});
					this.$nextTick(() => {
						this.$refs.putDialog.name = row.name;
						this.$refs.putDialog.dataId = id;
						this.$refs.putDialog.update(userRes);
					})
				} else {
					this.$nextTick(() => {
						this.$refs.putDialog.dataId = null;
						this.$refs.putDialog.init()
					})
				}
			},
			accountBindHandleSetter(row){
				console.log(442,row.ad_account)
				this.$confirm(this.$t(`当前广告ID为"${row.ad_account}",是否确认解绑`, { 
					handle: this.$t('views.public.delete')
				}), this.$t('public.prompt.title'), {
					confirmButtonText: this.$t('解绑'),
					cancelButtonText: this.$t('views.public.cancel'),
					type: 'warning'
				}).then(() => {
					console.log(530)
					this.$axios.post(`/api/delivery/dataSpread/accountBind/${row.id}`, {}).then(res => {
						console.log(533)
						this.$refs.xTable.clearFilter();
						this.getTableList(true);
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 1500,
							onClose: () => {
							}
						})
						console.log(542)
					}).catch(() => {})
				}).catch(() => {})
			},
			// 删除
			deleteHandleSetter(row) {
				this.$confirm(this.$t('public.prompt.info', {
					handle: this.$t('views.public.delete')
				}), this.$t('public.prompt.title'), {
					confirmButtonText: this.$t('views.public.confirm'),
					cancelButtonText: this.$t('views.public.cancel'),
					type: 'warning'
				}).then(() => {
					this.$axios.delete(`/api/delivery/dataSpread/delete/${row.id}`, {}).then(res => {
						this.$refs.xTable.clearFilter();
						this.getTableList();
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 1500,
							onClose: () => {
							}
						})
					}).catch(() => {})
				}).catch(() => {})
			}
		}
	}
</script>

<style lang="scss" scoped>
	:deep(span.vxe-cell--filter){
		display: none;
	}
</style>